package at.spengergasse.web.servlet.kunden;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import at.spengergasse.dao.KundenDao;
import at.spengergasse.dao.PlzDao;
import at.spengergasse.dao.derby.KundenDaoDerbyImpl;
import at.spengergasse.dao.derby.PlzDAODerbyImpl;
import at.spengergasse.model.Plz;
import at.spengergasse.web.EntryPointURLEnum;
import at.spengergasse.web.servlet.LoginServlet;

@SuppressWarnings("serial")
public abstract class AbstractKundenServlet extends LoginServlet
{
	protected Map<Long, String> mapPlz = new TreeMap<Long, String>();

	protected static KundenDao kundenDAO = new KundenDaoDerbyImpl();
	protected static PlzDao plzDAO = new PlzDAODerbyImpl();

	public AbstractKundenServlet() throws Exception
	{
		super();

	}

	protected void loadMapPlz()
	{
		log.debug("Starting: Laden der PlzMap");

		List<Plz> listPlz = new ArrayList<Plz>();
		listPlz = plzDAO.findAll(connection);

		Iterator<Plz> it = listPlz.iterator();

		while (it.hasNext())
		{
			Plz tempPlz = it.next();
			try
			{
				mapPlz.put(tempPlz.getId(), tempPlz.getPlz() + " "
						+ tempPlz.getOrt());
			} catch (Exception e)
			{
				throw new IllegalArgumentException(
						" Fehler beim Laden der plzMap " + e.getMessage());
			}

		}

	}

	protected Long checkKundenIdParam(HttpServletRequest req,
			HttpServletResponse resp) throws ServletException, IOException
	{
		Long kundenId = null;
		try
		{
			kundenId = Long.valueOf(req.getParameter(KundenFieldNames.ID));
		} catch (Exception e)
		{
			log.warn("problems with given customerId!", e);
		}

		if (kundenId == null)
		{
			redirectToKundenList(req, resp, "customer customerId");
			return null;
		}
		return kundenId;
	}

	protected void redirectToKundenList(HttpServletRequest req,
			HttpServletResponse resp) throws ServletException, IOException
	{
		redirectToKundenList(req, resp, null);
	}

	protected void redirectToKundenList(HttpServletRequest req,
			HttpServletResponse resp, String errorMessage)
			throws ServletException, IOException
	{
		if (errorMessage != null)
		{
			req.getSession(true).setAttribute("errorMessage", errorMessage);
		}
		resp.sendRedirect(EntryPointURLEnum.KUNDEN_LIST_ALL.getUrl());
	}

}
